import { createRouter, createWebHashHistory } from 'vue-router'
import { store } from '@/store'
import { loadComponent } from '@/utils/utils'
import { defaultRouter } from './permissionTools'
import login from './modules/login'
import resetPassword from './modules/resetPassword'
import home from './modules/test'
import enterprise from './modules/enterprise'
import notFound from './modules/notFound'
import qiankun from './modules/qiankun'
import withoutPermission from './modules/withoutPermission'
import assets from './modules/assets'

export const routerItemArr = [
  {
    path: '/',
    component: loadComponent('main', 'index'),
    redirect: '/assets/list',
    children: [
      ...assets,
      ...home,
      ...withoutPermission,
      ...qiankun,
      ...notFound,
    ]
  },
  ...login,
  ...resetPassword,
  ...enterprise,
]

const routerHash = createWebHashHistory()
const router = createRouter({
  history: routerHash,
  routes: routerItemArr,
  scrollBehavior() {
    return {
      top: 0,
    }
  }
})

router.beforeEach((to, from, next) => {
  // 1. 白名单列表绿灯
  const isDefaultRouter = defaultRouter.includes(to.path)
  // const { account: { openId } } = store.state as Record<string, any>
  if (isDefaultRouter) {
    next()
    return
  }
  // 2. 无权限时白名单验证
  // if (!openId) {
  //   next({ path: '/login' })
  //   return
  // }
  // 3. 栏目权限验证 动态路由
  const pass = Object.prototype.hasOwnProperty.call(store.state.permissionsRoutersMap, to.path)
  if (pass) {
    next()
    return
  }
  next()
  // 兜底路由无权限
  // next({ path: '/withoutPermission', replace: true })
})
export default router
